package com.ict.luxshare.btservice;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.csr.gaia.library.Gaia;
import com.csr.gaia.library.GaiaError;
import com.csr.gaia.library.GaiaLink;
import com.csr.gaia.library.GaiaPacket;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    private final static String TAG = "BtService";

    private BluetoothManager mBluetoothManager;
    private BluetoothAdapter mBluetoothAdapter;
    private static final int REQUEST_ENABLE_BT=1;
    private static final int SCAN_TIME=10000;
    private ArrayList<BluetoothDevice> mBluetoothDevices=new ArrayList<BluetoothDevice>();

    private Handler mHandler; //該Handler用來搜尋Devices10秒後，自動停止搜尋
    // common:在這邊設定的BroadcastReceiver用來收目前BT的情況

    GaiaLink mGaiaLink;
    //common:收取Gaia的整個Link

    //common:這邊用一個Handler來收取Gaia的所有訊息


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Log.d(TAG, "onCreate()");
        // Bluetooth adapter
        //mBtAdapter = ((BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE)).getAdapter();

        setContentView(R.layout.activity_main);

        if(!getPackageManager().hasSystemFeature(getPackageManager().FEATURE_BLUETOOTH_LE)){
            Toast.makeText(getBaseContext(),/*R.string.No_sup_ble*/"There is no BLE support",Toast.LENGTH_LONG).show();
            finish();
        }
        //利用getPackageManager().hasSystemFeature()檢查手機是否支援BLE設備，否則利用finish()關閉程式。

        //試著取得BluetoothAdapter，如果BluetoothAdapter==null，則該手機不支援Bluetooth
        //取得Adapter之前，需先使用BluetoothManager，此為系統層級需使用getSystemService
        mBluetoothManager=(BluetoothManager)this.getSystemService(BLUETOOTH_SERVICE);
        mBluetoothAdapter=mBluetoothManager.getAdapter();
        // 使用getAdapter()這個api，要修改選項如下：
        // File > Project Structure > Flavors > Min Sdk Version
        // 至少要API level 18以上

        if(mBluetoothAdapter==null){
            Toast.makeText(getBaseContext(),/*R.string.No_sup_Bluetooth*/ "No Bluetooth adapter!!",Toast.LENGTH_SHORT).show();
            finish();
            return;
        }//如果==null，利用finish()取消程式。

        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        filter.addAction(BluetoothDevice.ACTION_FOUND);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        //registerReceiver(mReceiver, filter);

        ArrayList<String> deviceName=new ArrayList<String>();   //此ArrayList屬性為String，用來裝Devices Name
        mHandler=new Handler();
    }

    @Override
    protected void onPostResume() {
        super.onPostResume();

        Log.d(TAG, "onPostResume()");

        //一般來說，只要使用到mBluetoothAdapter.isEnabled()就可以將BL開啟了，但此部分添加一個Result Intent
        //跳出詢問視窗是否開啟BL，因此該Intenr為BluetoothAdapter.ACTION.REQUEST_ENABLE
        if(!mBluetoothAdapter.isEnabled()){
            Intent intent=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(intent,REQUEST_ENABLE_BT); //再利用startActivityForResult啟動該Intent
        }

        ScanFunction(true); //使用ScanFunction(true) 開啟BLE搜尋功能，該Function在下面部分
        //common: 在這邊設定InterntFilter 把BluetoothAdapter加上，用來確認目前BT的情況
        //IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
        //this.registerReceiver(BtReceiver, filter);

        //呼叫Gaia的Libraray來取得GaiaLink
        mGaiaLink = GaiaLink.getInstance();
       //mGaiaLink.setReceiveHandler(mGaiaHandler);
    }

    BroadcastReceiver mReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            //找到設備
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                Log.d(TAG, "ACTION_FOUND scan");
                //BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                //if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                    //Log.v(TAG, "find device:" + device.getName() + device.getAddress());
                //}
            }
            else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) //搜索完成
            {
                Log.d(TAG, "ACTION_DISCOVERY_FINISHED scan");
            }
            else if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) //搜索完成
            {
                Log.d(TAG, "ACTION_STATE_CHANGED scan");
            }
            else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) //搜索完成
            {
                Log.d(TAG, "ACTION_DISCOVERY_STARTED scan");
            }
            //執行更新清單的代碼
        }
    };

    private boolean mScanning;
    //此為ScanFunction，輸入函數為boolean，如果true則開始搜尋，false則停止搜尋
    private void ScanFunction(boolean enable){
        Log.d(TAG, "ScanFunction("+ (enable? "true)":"false)"));
        if(enable){
            mHandler.postDelayed(new Runnable() { //啟動一個Handler，並使用postDelayed在10秒後自動執行此Runnable()
                @Override
                public void run() {
                    mBluetoothAdapter.startDiscovery();//停止搜尋
                    mScanning=false; //搜尋旗標設為false
                    //textView.setText("Stop Scan");
                    Log.d(TAG,"ScanFunction():Stop Scan");
                }
            },SCAN_TIME); //SCAN_TIME為幾秒後要執行此Runnable，此範例中為10秒
            mScanning=true; //搜尋旗標設為true
            mBluetoothAdapter.startLeScan(mLeScanCallback);//開始搜尋BLE設備
            //textView.setText("Scanning");
            Log.d(TAG, "Start Scan");
        }
        else {
            mScanning=false;
            mBluetoothAdapter.stopLeScan(mLeScanCallback);
        }
    }
//注意，在此enable==true中的Runnable是在10秒後才會執行，因此是先startLeScan，10秒後才會執行Runnable內的stopLeScan
//在BLE Devices Scan中，使用的方法為startLeScan()與stopLeScan()，兩個方法都需填入callback，當搜尋到設備時，都會跳到
//callback的方法中
//建立一個BLAdapter的Callback，當使用startLeScan或stopLeScan時，每搜尋到一次設備都會跳到此callback
    private ArrayList<String> mDeviceName;
    private BluetoothAdapter.LeScanCallback mLeScanCallback=new BluetoothAdapter.LeScanCallback() {
        @Override
        public void onLeScan(final BluetoothDevice device, final int rssi, byte[] scanRecord) {
            runOnUiThread(new Runnable() { //使用runOnUiThread方法，其功能等同於WorkThread透過Handler將資訊傳到MainThread(UiThread)中，
                //詳細可進到runOnUiThread中觀察
                @Override
                public void run() {
                    Log.d(TAG, "callback()");
                    if (!mBluetoothDevices.contains(device)) { //利用contains判斷是否有搜尋到重複的device
                        mBluetoothDevices.add(device);         //如沒重複則添加到bluetoothdevices中
                        Log.d(TAG, "device name: " + device.getName() + " ,rssi:" + rssi + "\r\n" + device.getAddress());
                        mDeviceName.add(device.getName() + " rssi:" + rssi + "\r\n" + device.getAddress()); //將device的Name、rssi、address裝到此ArrayList<Strin>中
                    }
                }
            });
        }
    };
}
